package com.jb.web.model.css.event;

import com.jb.web.bean.Form;
import com.jb.web.bean.HtmlItem;
import com.jb.web.bean.Panel;
import com.jb.web.bean.event.UIEvent;
import com.jb.web.context.WebContext;
import com.jb.web.form.BeanForm;
import com.jb.web.model.css.Style;

import java.beans.PropertyEditor;

import com.jb.faces.event.PhaseId;
import com.jb.web.application.DialogBoxApps;


public class StyleEditorEH {
    public void onColorChange(WebContext pCtx, UIEvent event) {
        PropertyEditor pe = (PropertyEditor) pCtx.getParameter(DialogBoxApps.PE_KEY);

        if (pe == null) {
            return;
        }

        if (pCtx.getPhase() == PhaseId.UPDATE_MODEL_VALUES) {
            String color = event.getParameter("colorValue");

            if (pe != null) {
                pe.setAsText(color);
            }
        } else //value to assigned to input field
         {
            Form form = (Form) event.getSource();
            HtmlItem htmlItem = (HtmlItem) form.getDescendantByClientId("colorValue");

            if (htmlItem != null) {
                htmlItem.setValue(pe.getAsText());
            }
        }
    }

    public void onPreview(WebContext pCtx, UIEvent event) {
        BeanForm form = (BeanForm) event.getSource();

        try {
            Style background = (Style) form.createBeanInstance(pCtx, event.getParameters());
            Panel samplePanel = (Panel) form.getDescendantByClientId("Sample");

            if (samplePanel != null) {
                samplePanel.setBackgroundStyle(background.getStyle());
            }
        } catch (Exception e) {
            pCtx.addErrorMessage(form, "Failed to get instance of " + form.getSourceClass());
        }
    }
}
